package com.huishi.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * get 方式调用
     *
     * @param url
     * @return
     */
    public static String sendGet(String url) {
        logger.info("=====================HTTP GET 请求参数 url=" + url);
        InputStream is = null;
        String body = null;
        StringBuilder res = new StringBuilder();
        // 实例化CloseableHttpClient
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 添加URL和请求参数
            //替换空格;get请求，url拼接参数时，参数值可能存在空格，需要对空格做处理，不然接口会调不通
            url = url.replaceAll(" ", "%20");
            URIBuilder ub = new URIBuilder(url);
            // 使用get方法添加URL
            HttpGet get = new HttpGet(ub.build());
            // 设置请求超时时间
            RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).build();
            get.setConfig(config);
            //使用http调用远程，获取相应信息
            response = client.execute(get);
            // 获取响应状态码，可根据是否响应正常来判断是否需要进行下一步
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                return "请求失败 statusCode=" + statusCode;
            }
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            // 读取响应内容
            if (entity != null) {
                is = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                while ((body = br.readLine()) != null) {
                    res.append(body);
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        logger.info("=====================HTTP GET 请求响应参数 result=" + res.toString());
        return res.toString();
    }

    /**
     * 发送post请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String sendPost(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        logger.info("post请求体json：{}",json);
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 发送post请求，接收响应二进制数据
     * @param url
     * @param json
     * @return
     */
    public static byte[] sendPostByte(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        byte[] res = null;
        logger.info("post请求体json：{}",json);
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            res = EntityUtils.toByteArray(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    /**
     * 发送post请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String sendPut(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        logger.info("post请求体json：{}",json);
        try {
            // 创建Http Put请求
            HttpPut httpPut = new HttpPut(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPut.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPut);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
}
